$(function () {
    var self;
    var oPage = {
        init: function () {
            self = this;
            self.bind();
            self.setPhoneresolving();
        },
        setPhoneresolving: function () {
            var r = $('.resolving').val();
            var width = r.split('*')[0];
            var height = r.split('*')[1];
            $('.phone-edit').css({
                width: width,
                margin: '0 auto',
                height: height
            });
            $('.phone-view').css({
                width: width,
                margin: '0 auto',
                height: height
            })
        },
        bind: function () {
            $('.resolving').on('change', function () {
                self.setPhoneresolving();
                // debugger

            })

        }
    };
    oPage.init();
    function initContainer() {
        $(".demo, .demo .column").sortable({
            connectWith: ".column",
            opacity: .35,
            handle: ".drag",
            start: function (e, t) {
                if (!startdrag) stopsave++;
                startdrag = 1;
            },
            stop: function (e, t) {
                if (stopsave > 0) stopsave--;
                startdrag = 0;
                downloadLayoutSrc()
            }
        });
        configurationElm();
    }
    function configurationElm(e, t) {
        $(".demo").delegate(".configuration > a", "click", function (e) {
            e.preventDefault();
            var t = $(this).parent().next().next().children();
            $(this).toggleClass("active");
            t.toggleClass($(this).attr("rel"))
        });
        $(".demo").delegate(".configuration .dropdown-menu a", "click", function (e) {
            e.preventDefault();
            var t = $(this).parent().parent();
            var n = t.parent().parent().next().next().children();
            t.find("li").removeClass("active");
            $(this).parent().addClass("active");
            var r = "";
            t.find("a").each(function () {
                r += $(this).attr("rel") + " "
            });
            t.parent().removeClass("open");
            n.removeClass(r);
            n.addClass($(this).attr("rel"))
        })
    }
    initContainer();
    $(".sidebar-nav .lyrow").draggable({
        connectToSortable: ".demo",
        helper: "clone",
        handle: ".drag",
        start: function (e, t) {
            if (!startdrag) stopsave++;
            startdrag = 1;
        },
        drag: function (e, t) {
            t.helper.width(400)
        },
        stop: function (e, t) {
            console.log(t)
            t.helper.removeAttr('style')
            $(".demo .column").sortable({
                opacity: .35,
                connectWith: ".column",
                start: function (e, t) {
                    if (!startdrag) stopsave++;
                    startdrag = 1;
                },
                stop: function (e, t) {
                    if (stopsave > 0) stopsave--;
                    startdrag = 0;

                }
            });
            if (stopsave > 0) stopsave--;
            startdrag = 0;
        }
    });
    $(".sidebar-nav .box").draggable({
        connectToSortable: ".column",
        helper: "clone",
        handle: ".drag",
        start: function (e, t) {
            // if (!startdrag) stopsave++;
            // startdrag = 1;
        },
        drag: function (e, t) {
            t.helper.width(400)
        },
        stop: function (e, t) {
            t.helper.removeAttr('style')
            // handleJsIds();
            // if(stopsave>0) stopsave--;
            // startdrag = 0;
            downloadLayoutSrc()
        }
    });
    function gridSystemGenerator() {
        $(".lyrow .preview input").bind("keyup", function () {
            var e = 0;
            var t = "";
            var n = $(this).val().split(" ", 12);
            $.each(n, function (n, r) {
                //  e = e + parseInt(r);
                if (r == 1) {
                    t += '<div class="flex felxbox column"></div>'
                } else {
                    t += '<div class="flex-' + r + ' felxbox column"></div>'
                }

            });
            // if (e == 12) {
            $(this).parent().next().children().html(t);
            //     $(this).parent().prev().show()
            // } else {
            //     $(this).parent().prev().hide()
            // }
        })
    }
    gridSystemGenerator();
    $("#downloadModal").click(function (e) {
        e.preventDefault();
        downloadLayoutSrc();
    });
    function cleanHtml(e) {
        $(e).parent().append($(e).children().html())
    }
    function createIframe(code) {
        var iframe = document.createElement('iframe');
        var iframedocument;
        var iframeWindow;
        // document.body.appendChild(iframe);
        $('.phone-view').html('')[0].appendChild(iframe)
        // $('.phone-view').html(iframe);
       iframe.setAttribute('frameborder','0')
        if (iframe.document) { //ie 8 chrome opera Safari (windows)

            iframedocument = iframe.document;//contentWindow.document;
            iframeWindow = iframe.contentWindow;
            var script = iframedocument.createElement('script');
            script.src = "/common_info/js/mx.im.inPoll.js";
            iframedocument.getElementsByTagName('head')[0].appendChild(script);

        } else {
            // chrome opera Safari firefox (windows and os)
            iframedocument = iframe.contentDocument;//contentWindow.document;
            iframeWindow = iframe.contentWindow;
            iframedocument.open();
            iframedocument.write('<html><head><title>im in_poll</title> <link href="./css/layout.css" rel="stylesheet"></head><body>'+code+'</body></html>');
            iframedocument.close();
        }
    }
    function changeStructure(e, t) {
        $("#download-layout ." + e).removeClass(e).addClass(t)
    }
    function downloadLayoutSrc() {
        var e = "";
        $("#download-layout").children().html($(".demo").html());
        var t = $("#download-layout").children();
        t.removeClass('container-fluid').addClass('ui-container')
        t.find(".preview, .configuration, .drag, .remove").remove();
        t.find(".lyrow").addClass("removeClean");
        t.find(".box-element").addClass("removeClean");
        t.find(".lyrow .lyrow .lyrow .lyrow .lyrow .removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".lyrow .lyrow .lyrow .lyrow .removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".lyrow .lyrow .lyrow .removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".lyrow .lyrow .removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".lyrow .removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".removeClean").each(function () {
            cleanHtml(this)
        });
        t.find(".removeClean").remove();
        $("#download-layout .column").removeClass("ui-sortable");
        $("#download-layout .row-fluid").removeClass("clearfix  row-fluid").children().removeClass("column");
        if ($("#download-layout .container").length > 0) {
            changeStructure("row-fluid", "row")
        }
        formatSrc = $.htmlClean($("#download-layout").html(), {
            format: true,
            allowedAttributes: [

                ["id"],
                ["class"],
                ["data-toggle"],
                ["data-target"],
                ["data-parent"],
                ["role"],
                ["data-dismiss"],
                ["aria-labelledby"],
                ["aria-hidden"],
                ["data-slide-to"],
                ["data-slide"]
            ]
        });
        $("#download-layout").html(formatSrc);
        $("#downloadModal textarea").empty();
        $("#downloadModal textarea").val(formatSrc);
        
        createIframe(formatSrc)
        console.log(formatSrc)
    }
    function supportstorage() {
        if (typeof window.localStorage=='object') 
            return true;
        else
            return false;		
    }
    var layouthistory;
    function saveLayout(){
        var data = layouthistory;
        if (!data) {
            data={};
            data.count = 0;
            data.list = [];
        }
        if (data.list.length>data.count) {
            for (i=data.count;i<data.list.length;i++)
                data.list[i]=null;
        }
        data.list[data.count] = window.demoHtml;
        data.count++;
        if (supportstorage()) {
            localStorage.setItem("layoutdata",JSON.stringify(data));
        }
        layouthistory = data;
       
    }
    var stopsave = 0;
    var startdrag = 0;
    function handleSaveLayout() {
        var e = $(".demo").html();
       if (!stopsave && e != window.demoHtml) {
           stopsave++;
           window.demoHtml = e;
            saveLayout();
           stopsave--;
       }
    }
    // setInterval(function() {
	// 	handleSaveLayout()
	// }, 2000)
})